/*
 * @Autor: dingxiaolin
 * @Date: 2020-12-24 20:46:14
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2020-12-25 00:41:01
 */
import firstletter from './dict.js'
/**
 * 延迟操作
 * @param {*} func 方法
 * @param {*} wait 延时时间
 * throttle(()=>{}, 1000)()
 */
export function throttle (func, wait) {
  let timeout
  return function () {
    let that = this
    let args = arguments

    if (!timeout) {
      timeout = setTimeout(function () {
        timeout = null
        func.apply(that, args)
      }, wait)
    }
  }
}
/**
 * 获取中文字符首字母拼音
 * @param {*} raw 
 * pinyin("丁晓林")[0].toUpperCase()
 * "D"
 * pinyin("丁晓林")
 * "DXL"
 */
export function pinyin (raw) {
  const str = `${raw}`
  if (!str || /^ +$/g.test(str)) {
    return ''
  }
  let result = []
  for (let i = 0; i < str.length; i++) {
    let unicode = str.charCodeAt(i)
    let char = str.charAt(i)
    if (unicode >= 19968 && unicode <= 40869) {
      char = firstletter.charAt(unicode - 19968)
    }
    result.push(char)
  }
  return result.join('')
}
/**
 * 判断是否是json型的string
 * @param {*} str 
 */
export function isJSON (str) {
  if (typeof str === 'string') {
    try {
      let obj = JSON.parse(str)
      return !!(typeof obj === 'object' && obj)
    } catch (e) {
      return false
    }
  }
}

export default {
  throttle,
  pinyin,
  isJSON
}
